<?PHP

class ItemDiscountBO extends BusinessObject{
  /* private function using in constructors*/
  function setAttributes(){
    $this->fields   = array(
			id                =>	items_discount_id,
			item_id           =>	items_discount_itemid,
			type			        =>	items_discount_type,
			amount            =>	items_discount_amount,
			startdate         =>	items_discount_startdate,
			finishdate        =>	items_discount_finishdate,
			active            =>	items_discount_active,
			descr				      =>	items_discount_descr,
			inclaff				    =>	items_discount_inclaff
		);

    BusinessObject::setAttributes();
  }
  /* constuctor */
  function ItemDiscountBO(){
    /** super(tableName) */
    BusinessObject::BusinessObject("items_discount");
    $this->setAttributes();
  }

  function checkDiscount($item_id,$start,$finish) //return true if all ok with date ranges.
  {
    $id = new ItemDiscountBO();
    $id->item_id   = $item_id;
	  $id->active    = 1;
	  $where = "('".$start." <".$id->fields["finishdate"]." and '".$start."' >=".$id->fields["startdate"].") OR ".
    "('".$finish."' <".$id->fields["startdate"]." and '".$finish."' >=".$id->fields["finishdate"].")";
    if($id->getCount($where)>0) return false;  //exist active discount with the same date range
    return(true);
  }

	function returnPrice ($item_id, $price, $date, $isaff) {
		$sd = new ItemDiscountBO();
		$sd->item_id   = $item_id;
		$sd->active    = 1;
		$where = "('".$date."'<".$sd->fields["finishdate"]." and '".$date."'>=".$sd->fields["startdate"].")";
		$sd->Load(0,0,"",$where);
		if ($sd->Next()) 
    {
			if ( !$isaff || $sd->inclaff == 1) {
				if ($sd->type == 0) {
					$amount = $price - (($price/100) * $sd->amount);
				} else {
					$amount = $price - $sd->amount;
				}
				return (round ($amount,2));
			} else {
				return $price;
			}
		} else {
			return $price;
		}
	}

	function returnDiscount ($item_id, $date,$isaff) {
		$sd = new ItemDiscountBO();
		$sd->item_id   = $item_id;
		$sd->active    = 1;
		$where = "('".$date."'<".$sd->fields["finishdate"]." and '".$date."'>=".$sd->fields["startdate"].")";
		$sd->Load(0,0,"",$where);
		if ($sd->Next()) 
    {
			if (!$isaff  || $sd->inclaff == 1) 
      {
				if ($sd->type == 0) {
					return ($sd->amount."%");
				} else {
					return ("$".$sd->amount);
				}
			} else 
      {
				return ("");
			}
		} else {
			return ("");
		}
	}
}
?>
